package com.shz.appletsapi.service;

import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.shz.appletsapi.common.utils.DateUtils;
import com.shz.appletsapi.model.po.LahuoMonitor;
import com.shz.appletsapi.prop.ShzProperties;
import com.shz.appletsapi.repository.LahuoMonitorRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class EmailService {
	
	@Autowired
	private JavaMailSender sender;
	
	@Autowired
	private ShzProperties shzProperties;
	
	@Autowired
	private LahuoMonitorRepository lahuoMonitorRepository;
	
	public void Send() throws MessagingException {
		List<LahuoMonitor> list=lahuoMonitorRepository.findByCreateDate(DateUtils.getYesDate());
		StringBuffer sb = new StringBuffer();
		sb.append("<html> ")
		        .append("<body> "
		        		+ "<table border='0' cellpadding='3' cellspacing='1' bgcolor='#c1c1c1'>")
		        .append("<tr bgcolor='#FFFFFF'>"
		        		+ "<th>appId</th>"
		        		+ "<th>content</th>"
		        		+ "<th>count</th>"
		        		+ "<th>createDate</th>"
		        		+ "</tr>");
		        for(LahuoMonitor la : list) {
		        sb.append("<tr bgcolor='#FFFFFF'>"
			        		+ "<td>"+la.getAppId()+"</td>"
			        		+ "<td>"+la.getContent()+"</td>"
			        		+ "<td>"+la.getCount()+"</td>"
			        		+ "<td>"+la.getCreateTime()+"</td>"
			        		+ "</tr>");
		        }
                sb.append("</table>"
                		+ "</body>"
                		+ "</html>");
        MimeMessage message = sender.createMimeMessage();
        
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
		for(String to : shzProperties.getToEmails()) {
			helper.setFrom("logssystem@scavengers.mobi");			
			helper.setTo(to);
			helper.setSubject("monitor");
			helper.setText(sb.toString(),true);
		        try {
		        	sender.send(message);
		            log.info("简单邮件已经发送。");
		        } catch (Exception e) {
		        	log.error("发送简单邮件时发生异常！", e);
		        }
		}
	}
	
	
	
	

}
